import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000,// request timeout

})

// 请求拦截器
service.interceptors.request.use(
  config => {

    if (store.getters.token) {

      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use((response) => {
  // 如果是 blob对象不是json 则直接返回
  if (response.data instanceof Blob) return response.data
  const { data, message, success } = response.data

  if (success) {
    return data
  } else {
    Message({ type: 'error', message })
    return Promise.reject(new Error(message))
  }
}, async (error) => {
  if (error.response.status === 401) {
    await store.dispatch('user/logout')
    router.push('/login')
    Message({ type: 'error', message: 'token超时了' })
    return Promise.reject(error)
  }
  Message({ type: 'error', message: error.message })
  return Promise.reject(error)
})

export default service
